<?php
/**
 * 产品分表
 * 分表规则：表名+公司id+语言名称
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/12/14
 * Time: 17:07
 */

namespace app\api\model;

use think\Db;
use think\Model;
use app\Config;
use PDO;

class Product extends Model
{
    public $pdo = '';
    public $dbName = '';

    public function __construct()
    {
        $dbms = $this->getConfig('type');     //数据库类型
        $host = $this->getConfig('hostname'); //数据库主机名
        $this->dbName = $this->getConfig('database');    //使用的数据库
        $this->pdo = new PDO("$dbms:host=$host;dbname=$this->dbName", $this->getConfig('username'), $this->getConfig('password'));
    }

    /**
     * 检测数据表是否存在
     * @param string $table
     * @return bool
     */
    public function checkTableExist($table = '')
    {
        $tableName = $table ? $table : self::getTable();
        $sql = sprintf("SELECT COUNT(1) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`='%s' AND `TABLE_NAME` = '%s'", $this->dbName, $this->getConfig('prefix') . $tableName);
        $result = $this->pdo->query($sql);
        if ($result === false) {//表不存在
            return false;
        }
        if (!$result->fetchColumn(0)) {
            return false;
        }
        return true;
    }

    /**
     * 复制表结构
     * @param string $table
     * @param string $newTable
     * @param string $company_id
     * @return bool
     */
    public function copyTable($table = '', $newTable = '', $company_id = '')
    {
        $table = $this->getConfig('prefix') . $table;
        $newTable = $this->getConfig('prefix') . $newTable;
        $sql = sprintf("create table %s like %s", $newTable, $table);
        $result = $this->pdo->query($sql);
        if ($result === false) {
            return false;
        }
        $sql = sprintf("alter table %s comment '%s'", $newTable, '公司-' . $company_id . "_" . $table . '分表');
        $this->pdo->query($sql);
        return true;
    }

    /**
     * 检测产品原始表，不存在创建
     * @param string $company_id
     * @return bool
     */
    public function checkProductTable($company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $productTbale . "_" . $company_id;

        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
        }
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $company_id);
        }
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $company_id);
        }
        if ($this->checkTableExist($newResourceTbale) == false) {
            $this->copyTable($resourceTbale, $newResourceTbale, $company_id);
        }
        return true;
    }

    /*************************************** api上传 *********************************************************/
    /**
     * 上传产品
     * @param $insertData
     * @param string $company_id
     */
    public function insertProduct($insertData, $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $productTbale . "_" . $company_id;
        //公司分表不存在
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
        }

        DB::name($newProductTable)->insert($insertData);
    }

    /**
     * 上传变体
     * @param $insertData
     * @param string $company_id
     * @param string $type
     */
    public function insertProperty($insertData, $company_id = '', $type = '')
    {
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $company_id);
        }

        if ($type == 'all') {
            DB::name($newPropertyTbale)->insertAll($insertData);
        } else {
            DB::name($newPropertyTbale)->insert($insertData);
        }
    }

    /**
     * 上传产品图
     * @param $insertData
     * @param string $company_id
     * @param string $type
     */
    public function insertImg($insertData, $company_id = '', $type = '')
    {
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $company_id);
        }
        if ($type == 'all') {
            DB::name($newProductImgTbale)->insertAll($insertData);
        } else {
            DB::name($newProductImgTbale)->insert($insertData);
        }
    }

    /**
     * 检测主产品是否有图片
     * @param string $guid
     * @param string $company_id
     * @return bool
     * @throws \think\Exception
     */
    public function checkProductImg($guid = '', $company_id = '')
    {
        $productImgTbale = 'img_' . $company_id;
        if ($this->checkTableExist($productImgTbale) == false) {
            return false;
        }
        $where['guid'] = $guid;
        $where['serial'] = 0;
        $res = Db::name($productImgTbale)->where($where)->count();
        return $res > 0 ? true : false;
    }

    /*************************************** 产品翻译 *********************************************************/
    /**
     * 获取翻译产品详细信息
     * @param string $guid
     * @param string $lang
     * @param string $company_id
     * @param string $user
     * @param string $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productInfoByFanyi($guid = '', $lang = '', $user = '', $company_id = '', $type = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;
        if ($this->checkTableExist($newProductTable) == false) {
            return $this->returnArr('UnTranslateNoProduce');
        }
        //主要数据
        $where['audit'] = 2;
        $where['user_name'] = $user;
        $where['guid'] = $guid;
        if ($type) {//获取单个产品数据
            $data = Db::name($newProductTable)->where($where)->find();
        } else {
            $data = Db::name($newProductTable)->field('guid,proname,content,keywords,sketch')->where($where)->find();
        }
        if (!checkArr($data)) {
            return $this->returnArr('UnTranslateNoProduce');
        }
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $propertys = [];
        } else {
            //获取变体信息
            $bwhere['lang'] = $lang ? $lang : 'moren';
            $bwhere['guid'] = $guid;
            if ($type) {
                $propertys = Db::name($newPropertyTbale)->where($bwhere)->order('serial asc')->select();
            } else {
                $propertys = Db::name($newPropertyTbale)->field('serial,cname')->where($bwhere)->order('serial asc')->select();
            }
        }
        $data['shuxing'] = $propertys;
        return $this->returnArr($data, true);
    }

    /**
     * 添加翻译产品数据
     * @param $productInfo
     * @param $data
     * @param $username
     * @param $company_id
     * @return array|bool
     * @throws \think\Exception
     */
    public function insertRenderingProduct($productInfo, $data, $username, $company_id)
    {
        $ylang = $data['lang'];//翻译产品语言
        $lang = $data['targetlang'];//翻译语言
        //产品表
        $productTbale = 'products';
        $productOldTbale = $ylang ? $productTbale . "_" . $ylang . "_" . $company_id : $productTbale . "_" . $company_id;
        $newProductTable = $productTbale . "_" . $lang . "_" . $company_id;
        //产品图表
        $productImgTbale = 'img';
        $newProductImgTbale = $productImgTbale . "_" . $company_id;
        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;

        //公司分表不存在
        if ($this->checkTableExist($productOldTbale) == false) {
            return $this->returnArr('UnTranslateNoProduce');
        }
        if ($this->checkTableExist($newProductTable) == false) {
            $this->copyTable($productTbale, $newProductTable, $company_id);
        }
        if ($this->checkTableExist($newProductImgTbale) == false) {
            $this->copyTable($productImgTbale, $newProductImgTbale, $company_id);
        }
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $this->copyTable($propertyTbale, $newPropertyTbale, $company_id);
        }
        //检测当前产品在语言表中是否存在
        $res = Db::name($newProductTable)->where('guid', $data['guid'])->count('id');

        $ylang = $ylang ? $ylang : 'moren';
        if ($res == 0) {//不存在，新建数据
            //新建主数据
            $insertData = array(
                'source' => $productInfo['source'],
                'proname' => $data['proname'],
                'tmd5' => md5($data['proname']),
                'sketch' => transitionbr($data['sketch']),
                'keywords' => transitionbr($data['keywords']),
                'content' => transitionbr($data['content']),
                'user_name' => $username,
                'ndate' => date("Y-m-d", time()),
                'audit' => 2,
                'guid' => $data['guid'],
                'title' => $productInfo['title'],
                'skucode' => $productInfo['skucode'],
                'price' => $productInfo['price'],
                'saleprice' => $productInfo['saleprice'],
                'coin' => $productInfo['coin'],
                'code' => $productInfo['code'],
                'kucun' => $productInfo['kucun'],
                'weight' => $productInfo['weight'],
                'btname' => $productInfo['btname'],
                'bname' => $productInfo['bname'],
                'platform' => $productInfo['platform']
            );
            $insertData['repeat'] = $this->checkProduct($insertData['tmd5'], $username, $company_id, $lang);
            DB::name($newProductTable)->insert($insertData);

            //新建变体数据
            //检测是否存在变体
            if (checkArr($productInfo['shuxing'])) {
                $shuxing = arrayCombine($productInfo['shuxing'], 'serial');
                foreach ($shuxing as $value) {
                    isset($shuxing[$value['serial']]['cname']) && $value['cname'] = $shuxing[$value['serial']]['cname'];
                    $insertShuxing[] = array(
                        'serial' => $value['serial'],
                        'cname' => $value['cname'],
                        'price' => $value['price'],
                        'saleprice' => $value['saleprice'],
                        'kucun' => $value['kucun'],
                        'skucode' => $value['skucode'],
                        'weight' => $value['weight'],
                        'carriage' => $value['carriage'],
                        'cost' => $value['cost'],
                        'lang' => $lang,
                        'guid' => $value['guid']
                    );
                }
                DB::name($newPropertyTbale)->insertAll($insertShuxing);
            }

            //新建图片数据
            //检测产品图片是否存在
            $where = ['guid' => $data["guid"], 'lang' => $ylang];
            $img = Db::name($newProductImgTbale)->where($where)->count('guid');
            if ($img != 0) {
                $sql2 = "INSERT INTO " . $this->getConfig('prefix') . $newProductImgTbale . "(lang,resource_id,guid,serial,px) SELECT '" . $lang . "',resource_id,guid,serial,px FROM  " . $this->getConfig('prefix') . $newProductImgTbale . " WHERE guid='" . $data["guid"] . "' AND lang='" . $ylang . "'";
                $this->pdo->exec($sql2);
            }
            //更改翻译产品状态
            $fanyi = checkString($productInfo['fanyi']) ? explode(',', $productInfo['fanyi']) : [];
            $fanyi[] = $lang;
            DB::name($productOldTbale)->where('guid', $data["guid"])->update(['fanyi' => join(',', array_unique($fanyi))]);

            return $this->returnArr('TranslateOK');
        } else {//更新数据
            return $this->returnArr('TranslateOKed ');
        }
    }

    /*************************************** 通用方法 *********************************************************/

    /**
     * 获取产品全部信息
     * @param string $guid
     * @param string $lang
     * @param string $company_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function productInfo($guid = '', $lang = '', $company_id = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;

        if ($this->checkTableExist($newProductTable) == false) {
            return $this->returnArr('UnTranslateNoProduce');//当前数据不存在
        }
        //主要数据
        $data = Db::name($newProductTable)->where('guid', $guid)->find();
        if (!checkArr($data)) {
            return $this->returnArr('UnTranslateNoProduce');
        }

        //属性表
        $propertyTbale = 'shuxing';
        $newPropertyTbale = $propertyTbale . "_" . $company_id;
        if ($this->checkTableExist($newPropertyTbale) == false) {
            $propertys = [];
        } else {
            //获取变体信息
            $where['lang'] = $lang ? $lang : 'moren';
            $where['guid'] = $guid;
            $propertys = Db::name($newPropertyTbale)->where($where)->order('serial asc')->select();
            $propertys = checkArr($propertys) ? arrayCombine($propertys, 'serial') : [];
        }
        $data['imgs'] = [];
        //资源表
        $resourceTbale = "resource";
        $newResourceTbale = $resourceTbale . "_" . $company_id;
        if ($this->checkTableExist($newResourceTbale) == false) {
            $imgs = [];//图片信息
        } else {
            //图片信息
            $productImgTbale = 'img';
            $newProductImgTbale = $productImgTbale . "_" . $company_id;
            if ($this->checkTableExist($newProductImgTbale) == false) {
                $imgs = [];//图片信息
            } else {
                $imgs = Db::name($newProductImgTbale)->where($where)->order('px asc')->select();
            }
        }
        if (checkArr($imgs)) {
            $resource_ids = array_unique(array_column($imgs, 'resource_id'));
            $resource = Db::name($newResourceTbale)
                ->where(['id' => ['in', join(',', $resource_ids)]])
                ->select();
            $resources = arrayCombine($resource, 'id');
            foreach ($imgs as $key => $value) {
                $resource = isset($resources[$value['resource_id']]) ? $resources[$value['resource_id']] : [];
                if ($value['serial'] == 0) {
                    checkArr($resource) && $data['imgs'][] = ['resource' => $resource, 'px' => $value['px'], 'resource_id' => $value['resource_id']];
                }
                if (checkArr($resource) && $value['serial'] > 0 && isset($propertys[$value['serial']])) {
                    $resource['px'] = $value['px'];
                    $propertys[$value['serial']]['imgs'][] = $resource;
                }
            }
        }
        $data['shuxing'] = $propertys;
        return $this->returnArr($data, true);
    }

    /**
     * 检测产品是否存在
     * @param string $tmd5
     * @param string $username
     * @param string $company_id
     * @param string $lang
     * @return bool
     * @throws \think\Exception
     */
    public function checkProduct($tmd5 = '', $username = '', $company_id = '', $lang = '')
    {
        //产品表
        $productTbale = 'products';
        $newProductTable = $lang ? $productTbale . "_" . $lang . "_" . $company_id : $productTbale . "_" . $company_id;
        if ($this->checkTableExist($newProductTable) == false) {
            return false;
        }
        $where['user_name'] = $username;
        $where['tmd5'] = $tmd5;
        $res = DB::name($newProductTable)->where($where)->count('id');
        if ($res > 0) {
            return true;
        }
        return false;
    }

    /**
     * 信息返回
     * @param string $msg
     * @param bool $state
     * @return array
     */
    public function returnArr($msg = '', $state = false)
    {
        return ['state' => $state, 'content' => $msg];
    }
}